package com.apache.passport.service.plugins;

import java.util.HashMap;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.apache.api.api.SystemService.ParamType;
import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.Validator;
import com.apache.database.db.IDao;
import com.apache.passport.aop.LoginAopTimer;
import com.apache.passport.entity.SynInfo;
import com.apache.passport.entity.UctUser;
import com.apache.passport.manager.SynInfoManager;
import com.apache.rpc.server.protocl.AbstractProtocolService;
import com.apache.rpc.server.protocl.HttpProtocolService;
import com.apache.rpc.server.protocl.HttpsProtocolService;
import com.apache.rpc.server.protocl.SocketProtocolService;
import com.apache.rpc.server.protocl.WebServiceProtocolService;

/**
 * description:  用户信息同步
 * @author Hou Dayu 创建时间：2014-12-23  
 * @Copyright(c)2014:
 */
public class SynInfoPlugin implements PluginConnector {
	private static final Logger log = LoggerFactory.getLogger(LoginAopTimer.class);

	protected IDao synInfoDao;
	private SynInfoManager synInfoManager;

	public void setSynInfoDao(IDao synInfoDao) {
		this.synInfoDao = synInfoDao;
	}

	public void setSynInfoManager(SynInfoManager synInfoManager) {
		this.synInfoManager = synInfoManager;
	}

	@Override
	public Object execute(ParamsVo arg0) throws Exception {
		String sysEname = (String) arg0.getParams("sysEname");
		UctUser uctUser = (UctUser) arg0.getParams("user");
		//客户端返回信息
		String rtn = "";
		ResultEntity result = new ResultEntity();
		if (!Validator.isEmpty(sysEname)) {

			Map<String, AbstractProtocolService> services = new HashMap<String, AbstractProtocolService>();
			services.put("http", new HttpProtocolService());
			services.put("https", new HttpsProtocolService());
			services.put("socket", new SocketProtocolService());
			services.put("webservice", new WebServiceProtocolService());
			SynInfo synInfo = new SynInfo();
			ParamsVo<SynInfo> mvo = new ParamsVo<SynInfo>();
			mvo.setParams("sysEname", sysEname);
			mvo.setMethodKey("sysEnameQuery");
			result = (ResultEntity) synInfoManager.execute(mvo);
			if (result.getEntity() instanceof SynInfo) {
				synInfo = (SynInfo) result.getEntity();
				AbstractProtocolService ps = (AbstractProtocolService) services.get(synInfo.getSynUseAgree());
				ps.setHttpIp(synInfo.getSynSeraddr());
				ps.setHttpProt(synInfo.getSynSockport());
				ps.setHttpUrl(synInfo.getSynSeraddr());
				String sndMsg = pariseXml(uctUser, synInfo.getSynParamet());
				log.info("send data:[{}]", sndMsg);
				rtn = ((AbstractProtocolService) services.get(synInfo.getSynUseAgree())).doService(sndMsg,
						ParamType.XML);

				if (Validator.isNull(rtn)) {
					result.setMessage("发送失败或客户端为异常");
					log.info("passport msg:[{}]", "发送失败或客户端为异常");
				} else {
					result.setMessage("发送成功");
					log.info("passport msg:[{}]", "发送成功");
				}

				result.setEntity(rtn);
				log.info("receive msg:[{}]", rtn);
			}

			//			ps.setHttpIp(register.getAddress());
			//			ps.setHttpProt(register.getPort());
			//			ps.setHttpUrl(register.getAddress());
			//			String result = ((AbstractProtocolService) services.get(register.getCallType())).doService(params,
			//					resultType);

		}
		return result;
	}

	/**
	 * description:拼接发送的报文  
	 * @param uctUser
	 * @param synParamet
	 * @return  
	 * @author Hou Dayu 
	 * @update 2014-12-29
	 */
	private String pariseXml(UctUser uctUser, String synParamet) {
		String xml = "";
		Document doc = new Document();
		Element root = new Element("xml-body");
		Element head = new Element("Head");
		Element body = new Element("Body");
		//头 begin
		Element version = new Element("Version");
		version.setText("1.0");
		Element methodCode = new Element("MethodCode");
		methodCode.setText("userOwRegService");
		Element beanId = new Element("BeanId");
		beanId.setText("ssoService");
		Element paramType = new Element("ParamType");
		paramType.setText("xml");

		head.addContent(version);
		head.addContent(methodCode);
		head.addContent(beanId);
		head.addContent(paramType);
		//头 end

		//体 begin,参数列表用","半角逗号分隔
		String[] param = synParamet.split(",");
		//获取当前对象中所有的值
		Map<String, String> map = uctUser.getValues(uctUser);
		for (int i = 0; i < param.length; i++) {
			Element bodyChild = null;
			if (Validator.isNull(param[i])) {
				bodyChild = new Element("<Null" + i + ">");
				bodyChild.setText("此值key为null或空格");
			} else {
				bodyChild = new Element(param[i]);
				bodyChild.setText(map.get(param[i]) == null ? "" : map.get(param[i]));
			}
			body.addContent(bodyChild);
		}
		//		Element userEname = new Element("userEname");
		//		userEname.setText(uctUser.getUserEname());
		//		Element email = new Element("email");
		//		email.setText(uctUser.getEmail());
		//		Element mobile = new Element("mobile");
		//		mobile.setText(uctUser.getMobile());
		//		Element userPass = new Element("userPass");
		//		userPass.setText(uctUser.getUserPass());
		//Element userCname = new Element("userCname");
		//Native2AsciiUtils.getInstance().native2Ascii(msg)
		//		body.addContent(userEname);
		//		body.addContent(email);
		//		body.addContent(mobile);
		//		body.addContent(userPass);
		//体 end
		root.addContent(head);
		root.addContent(body);

		doc.addContent(root);
		XMLOutputter outputter = null;
		Format format = Format.getRawFormat();
		format.setEncoding("UTF-8");
		format.setIndent("    ");
		outputter = new XMLOutputter(format);
		xml = outputter.outputString(doc);
		return xml;
	}
}
